package com.heima.article.service.impl;

import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.minio.MinIOFileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.utils.common.JsonUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOFileStorageService minIOFileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;


    /**
     * 文章模板填充保存Minio
     */
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content) {

        if (apArticle != null && StringUtils.isNotEmpty(content)) {
            try {
                //加载模板文件
                Template template = configuration.getTemplate("article.ftl");


                //创建Map集合存储模板需要的数据
                List<Map> articleContent = JsonUtils.toList(content, Map.class);

                Map<String, Object> date = new HashMap<>();
                date.put("content", articleContent);

                //将模板缓存到内存中
                StringWriter writer = new StringWriter();
                //生成模板
                template.process(date, writer);

                //上传到MinIO，获取url访问地址
                String fileName = apArticle.getId() + ".html";
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(writer.toString().getBytes());

                //上传图片
                String htmlFileUrl = minIOFileStorageService.uploadHtmlFile("", fileName, byteArrayInputStream);
                System.out.println(htmlFileUrl);

                //判断文章是否有残留静态页面
                String staticUrl = apArticle.getStaticUrl();
                if (StringUtils.isNotBlank(staticUrl)){
                    //删除原来的静态页
                    minIOFileStorageService.delete(staticUrl);
                }
                //添加静态页
                apArticle.setStaticUrl(htmlFileUrl);
                apArticleMapper.updateById(apArticle);

                //释放资源
                byteArrayInputStream.close();
                writer.close();
            } catch (Exception e) {
                log.error("生成静态页失败，{}", e.getMessage());
                throw new RuntimeException(e);
            }
        }
    }
}
